#include <stdio.h>  
#include <stdlib.h>  
  
// 观察者结构体  
typedef struct Observer {  
    void (*update)(struct Observer *self, int state);  
    struct Observer *next;  
} Observer;  
  
// 主题结构体  
typedef struct Subject {  
    Observer *observers;  
    int state;  
    void (*notify)(struct Subject *self);  
    void (*setState)(struct Subject *self, int newState);  
} Subject;  
  
// 辅助函数：添加到观察者列表  
void addObserver(Subject *subject, Observer *observer) {  
    // 简化添加逻辑，不考虑性能优化  
    if (subject->observers == NULL) {  
        subject->observers = observer;  
    } else {  
        Observer *current = subject->observers;  
        while (current->next != NULL) {  
            current = current->next;  
        }  
        current->next = observer;  
    }  
}  
  
// 辅助函数：通知所有观察者  
void notifyObservers(Subject *subject) {  
    Observer *current = subject->observers;  
    while (current != NULL) {  
        current->update(current, subject->state);  
        current = current->next;  
    }  
}  
  
// 主题方法实现  
void Subject_notify(Subject *self) {  
    notifyObservers(self);  
}  
  
void Subject_setState(Subject *self, int newState) {  
    self->state = newState;  
    Subject_notify(self);  
}  
  
// 观察者更新函数  
void Observer1_update(Observer *self, int state) {  
    (void)self; // 避免未使用参数的警告  
    printf("Observer1: State changed to %d\n", state);  
}  
  
void Observer2_update(Observer *self, int state) {  
    (void)self; // 避免未使用参数的警告  
    printf("Observer2: State changed to %d\n", state);  
}  
  
int main() {  
    // 初始化主题  
    Subject subject = {NULL, 0, Subject_notify, Subject_setState};  
  
    // 创建观察者  
    Observer *obs1 = (Observer *)malloc(sizeof(Observer));  
    obs1->update = Observer1_update;  
    obs1->next = NULL;  
  
    Observer *obs2 = (Observer *)malloc(sizeof(Observer));  
    obs2->update = Observer2_update;  
    obs2->next = NULL;  
  
    // 将观察者添加到主题中  
    addObserver(&subject, obs1);  
    addObserver(&subject, obs2);  
  
    // 改变主题状态并通知观察者  
    subject.setState(&subject, 10);  
  
    // 释放观察者内存  
    free(obs1);  
    free(obs2);  
  
    return 0;  
}